const { contextBridge,ipcRenderer } = require('electron')
const fs = require('fs')
const path = require('path')
window.ipcRenderer=ipcRenderer
document.addEventListener('DOMContentLoaded', () => {
  eventListener("zoomOut",'click', () => {
    ipcRenderer.send('set-zoom-out', false)
  })
  eventListener("zoomIn",'click', () => {
    ipcRenderer.send('set-zoom-in', false)
  })
  eventListener("close",'click', () => {
    ipcRenderer.send('set-close')
  })
})

function eventListener(domId,eventName,handler){
  $(domId).addEventListener(eventName,handler)
}

function $(domId){
  let dom = document.getElementById(domId)
  return dom == null ? {} : dom;
}
async function exitsFolder(reaPath) {
  const absPath = path.resolve(__dirname, reaPath);
  try {
    await fs.promises.stat(absPath)
  } catch (e) {
    // 不存在文件夹，直接创建 {recursive: true} 这个配置项是配置自动创建多个文件夹
    await fs.promises.mkdir(absPath, {recursive: true})
  }
}
contextBridge.exposeInMainWorld('api', {
  saveToLocal: async (pathStr="/home/caoyangjie/桌面/text.txt", content ='weweweew') => {
    let dir = pathStr.slice(0,pathStr.lastIndexOf('/'))
    await  exitsFolder(dir)
    fs.writeFileSync(pathStr, content);
  },
  toggle: ()=>ipcRenderer.invoke('dark-mode:toggle'),
  system: ()=>ipcRenderer.invoke('dark-mode:system')
})


